// 全局变量
let currentPage = 1;
const pageSize = 10;
let totalPages = 1;
let currentPolicies = [];
let currentSortColumn = '';
let currentSortDirection = 'asc';
let currentSelectedPolicy = null;

// 渲染策略列表
function renderPolicyList(policies) {
    // 保存当前策略列表
    currentPolicies = policies;
    
    // 计算总页数
    totalPages = Math.ceil(policies.length / pageSize);
    
    // 确保当前页码有效
    if (currentPage > totalPages) {
        currentPage = totalPages > 0 ? totalPages : 1;
    }
    
    // 获取当前页的数据
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pagePolicies = policies.slice(startIndex, endIndex);
    
    // 获取表格容器
    const tableBody = document.getElementById('policy-list-container');
    
    if (!tableBody) {
        console.error('表格容器未找到');
        return;
    }
    
    if (policies.length === 0) {
        // 显示空状态
        tableBody.innerHTML = `
            <div class="col-span-12 py-10 text-center text-text-secondary">
                <div class="mb-4 animate-float">
                    <i class="fa fa-search text-6xl text-primary\/20"></i>
                </div>
                <p>暂无策略数据</p>
                <p class="text-sm mt-1">点击"创建策略"按钮开始创建</p>
            </div>
        `;
        
        // 隐藏分页控件
        const paginationContainer = document.getElementById('pagination-container');
        if (paginationContainer) {
            paginationContainer.classList.add('hidden');
        }
        
        return;
    }
    
    // 生成表格内容
    let html = `
        <div class="grid grid-cols-12 text-xs font-medium text-text-secondary border-b border-border\/20 py-3">
            <div class="col-span-1 px-3">
                <input type="checkbox" class="rounded text-primary focus:ring-primary" id="select-all">
            </div>
            <div class="col-span-2 px-3">策略名称</div>
            <div class="col-span-2 px-3">策略类型</div>
            <div class="col-span-1 px-3">优先级</div>
            <div class="col-span-1 px-3">状态</div>
            <div class="col-span-2 px-3">检测通道</div>
            <div class="col-span-2 px-3">最后修改时间</div>
            <div class="col-span-1 px-3 text-right">操作</div>
        </div>
    `;
    
    // 添加策略行
    pagePolicies.forEach(policy => {
        const isSelected = currentSelectedPolicy === policy.id;
        const priorityClass = policy.priority === 1 ? 'bg-red-100 text-red-800' : 
                              policy.priority === 2 ? 'bg-yellow-100 text-yellow-800' : 
                              'bg-blue-100 text-blue-800';
        const statusClass = policy.status === 'enabled' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800';
        const statusText = policy.status === 'enabled' ? '已启用' : '已禁用';
        
        html += `
            <div class="grid grid-cols-12 py-3 border-b border-border\/20 hover:bg-primary\/5 transition-colors duration-200 policy-row ${isSelected ? 'bg-primary\/10' : ''}" data-id="${policy.id}">
                <div class="col-span-1 px-3 flex items-center">
                    <input type="checkbox" class="policy-checkbox rounded text-primary focus:ring-primary" data-id="${policy.id}">
                </div>
                <div class="col-span-2 px-3 flex items-center">
                    <div class="policy-name-container max-w-full truncate">
                        <span class="font-medium text-text-primary policy-name-text">${policy.name}</span>
                        <button class="edit-name-btn ml-2 text-text-secondary hover:text-primary transition-colors duration-300 opacity-0 hover:opacity-100" title="编辑名称" data-id="${policy.id}">
                            <i class="fa fa-pencil text-xs"></i>
                        </button>
                    </div>
                </div>
                <div class="col-span-2 px-3 flex items-center">${policy.type}</div>
                <div class="col-span-1 px-3 flex items-center">
                    <span class="px-2 py-1 rounded-full text-xs ${priorityClass}">P${policy.priority}</span>
                </div>
                <div class="col-span-1 px-3 flex items-center">
                    <span class="px-2 py-1 rounded-full text-xs ${statusClass}">${statusText}</span>
                </div>
                <div class="col-span-2 px-3 flex items-center">
                    <span class="truncate">${policy.channels?.join(', ') || '未设置'}</span>
                </div>
                <div class="col-span-2 px-3 flex items-center">${policy.lastModified}</div>
                <div class="col-span-1 px-3 flex items-center justify-end gap-1">
                    <button class="text-text-secondary hover:text-primary transition-colors duration-300 p-1 rounded" title="编辑策略" onclick="editPolicy(${policy.id})"><i class="fa fa-edit text-xs"></i></button>
                    <button class="text-text-secondary hover:text-primary transition-colors duration-300 p-1 rounded" title="复制策略" onclick="copyPolicy(${policy.id})"><i class="fa fa-copy text-xs"></i></button>
                    <button class="text-text-secondary hover:text-red-500 transition-colors duration-300 p-1 rounded" title="删除策略" onclick="deletePolicy(${policy.id})"><i class="fa fa-trash text-xs"></i></button>
                </div>
            </div>
        `;
    });
    
    tableBody.innerHTML = html;
    
    // 更新分页控件
    updatePagination();
    
    // 更新总数显示
    updateTotalCount();
    
    // 绑定事件
    bindPolicyRowEvents();
}

// 更新分页控件
function updatePagination() {
    const paginationContainer = document.getElementById('pagination-container');
    
    if (!paginationContainer) {
        // 如果分页容器不存在，创建它
        const tableContainer = document.querySelector('.border-x.border-b.border-border\/20').parentElement;
        if (tableContainer) {
            const paginationDiv = document.createElement('div');
            paginationDiv.id = 'pagination-container';
            paginationDiv.className = 'flex justify-between items-center mt-4 px-4';
            tableContainer.appendChild(paginationDiv);
            paginationContainer = paginationDiv;
        }
    }
    
    if (paginationContainer) {
        // 显示分页控件
        paginationContainer.classList.remove('hidden');
        
        let html = `
            <div class="text-sm text-text-secondary">
                显示 ${(currentPage - 1) * pageSize + 1}-${Math.min(currentPage * pageSize, currentPolicies.length)} 条，共 ${currentPolicies.length} 条
            </div>
            <div class="flex items-center gap-2">
                <button id="prev-page" class="px-3 py-1 text-sm rounded border border-border hover:border-primary hover:text-primary transition-colors duration-300 ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}">
                    <i class="fa fa-chevron-left mr-1"></i> 上一页
                </button>
                <button id="next-page" class="px-3 py-1 text-sm rounded border border-border hover:border-primary hover:text-primary transition-colors duration-300 ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}">
                    下一页 <i class="fa fa-chevron-right ml-1"></i>
                </button>
            </div>
        `;
        
        paginationContainer.innerHTML = html;
        
        // 绑定分页事件
        document.getElementById('prev-page').addEventListener('click', function() {
            if (currentPage > 1) {
                currentPage--;
                renderPolicyList(currentPolicies);
            }
        });
        
        document.getElementById('next-page').addEventListener('click', function() {
            if (currentPage < totalPages) {
                currentPage++;
                renderPolicyList(currentPolicies);
            }
        });
    }
}

// 重置分页
function resetPagination() {
    currentPage = 1;
}

// 选择策略
function selectPolicy(policyId) {
    currentSelectedPolicy = policyId;
    
    // 更新行样式
    document.querySelectorAll('.policy-row').forEach(row => {
        if (parseInt(row.dataset.id) === policyId) {
            row.classList.add('bg-primary/10');
        } else {
            row.classList.remove('bg-primary/10');
        }
    });
    
    // 显示策略详情
    showPolicyDetails(policyId);
}

// 显示策略详情
function showPolicyDetails(policyId) {
    const policy = currentPolicies.find(p => p.id === policyId);
    if (!policy) return;
    
    const detailPanel = document.getElementById('policy-detail-panel');
    if (!detailPanel) return;
    
    const detailContainer = detailPanel.querySelector('.p-4 > div:last-child');
    if (!detailContainer) return;
    
    // 构建详情HTML
    let html = `
        <div class="space-y-6">
            <div>
                <h3 class="text-lg font-semibold text-text-primary mb-2">策略基本信息</h3>
                <div class="space-y-3 text-sm">
                    <div class="grid grid-cols-4 gap-2">
                        <span class="text-text-secondary">策略名称：</span>
                        <span class="col-span-3 font-medium">${policy.name}</span>
                    </div>
                    <div class="grid grid-cols-4 gap-2">
                        <span class="text-text-secondary">策略类型：</span>
                        <span class="col-span-3">${policy.type}</span>
                    </div>
                    <div class="grid grid-cols-4 gap-2">
                        <span class="text-text-secondary">创建时间：</span>
                        <span class="col-span-3">${policy.createdAt || '未知'}</span>
                    </div>
                    <div class="grid grid-cols-4 gap-2">
                        <span class="text-text-secondary">最后修改：</span>
                        <span class="col-span-3">${policy.lastModified}</span>
                    </div>
                </div>
            </div>
            
            <div>
                <h3 class="text-lg font-semibold text-text-primary mb-2">策略配置</h3>
                <div class="space-y-3 text-sm">
                    <div class="grid grid-cols-4 gap-2">
                        <span class="text-text-secondary">优先级：</span>
                        <span class="col-span-3">P${policy.priority}</span>
                    </div>
                    <div class="grid grid-cols-4 gap-2">
                        <span class="text-text-secondary">状态：</span>
                        <span class="col-span-3">${policy.status === 'enabled' ? '已启用' : '已禁用'}</span>
                    </div>
                    <div class="grid grid-cols-4 gap-2">
                        <span class="text-text-secondary">检测通道：</span>
                        <span class="col-span-3">${policy.channels?.join(', ') || '未设置'}</span>
                    </div>
                </div>
            </div>
            
            <div>
                <h3 class="text-lg font-semibold text-text-primary mb-2">检测规则</h3>
                <div class="bg-background p-3 rounded border border-border/20 text-sm">
                    ${policy.rules ? policy.rules.map((rule, index) => `
                        <div class="mb-3 pb-3 border-b border-border/20 last:border-0 last:mb-0 last:pb-0">
                            <div class="font-medium mb-1">规则 ${index + 1}</div>
                            <div class="space-y-1 pl-4">
                                <div><span class="text-text-secondary">条件：</span>${rule.condition || '无'}</div>
                                <div><span class="text-text-secondary">操作：</span>${rule.action || '无'}</div>
                            </div>
                        </div>
                    `).join('') : '<p class="text-text-secondary">暂无规则</p>'}
                </div>
            </div>
            
            <div>
                <h3 class="text-lg font-semibold text-text-primary mb-2">策略说明</h3>
                <div class="bg-background p-3 rounded border border-border/20 text-sm">
                    ${policy.description || '<p class="text-text-secondary">暂无说明</p>'}
                </div>
            </div>
        </div>
    `;
    
    detailContainer.innerHTML = html;
        }

// 更新总数显示
function updateTotalCount() {
    const totalCountElement = document.querySelector('.text-text-secondary.text-sm');
    if (totalCountElement) {
        totalCountElement.textContent = `共 ${currentPolicies.length} 条策略`;
    }
}

// 绑定策略行事件
function bindPolicyRowEvents() {
    // 绑定行点击事件
    document.querySelectorAll('.policy-row').forEach(row => {
        row.addEventListener('click', function(e) {
            // 如果点击的是复选框或按钮，不触发选择
            if (e.target.type === 'checkbox' || e.target.closest('button')) {
                return;
            }
            const policyId = parseInt(this.dataset.id);
            selectPolicy(policyId);
        });
    });
    
    // 绑定编辑名称按钮悬停显示
    document.querySelectorAll('.policy-name-container').forEach(container => {
        container.addEventListener('mouseenter', function() {
            const editBtn = this.querySelector('.edit-name-btn');
            if (editBtn) {
                editBtn.style.opacity = '1';
            }
        });
        
        container.addEventListener('mouseleave', function() {
            const editBtn = this.querySelector('.edit-name-btn');
            if (editBtn) {
                editBtn.style.opacity = '0';
            }
        });
    });
    
    // 绑定编辑名称按钮点击事件
    document.querySelectorAll('.edit-name-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            const policyId = parseInt(this.dataset.id);
            enablePolicyNameEdit(policyId);
        });
    });
    
    // 绑定全选/取消全选
    const selectAllCheckbox = document.getElementById('select-all');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            const isChecked = this.checked;
            document.querySelectorAll('.policy-checkbox').forEach(checkbox => {
                checkbox.checked = isChecked;
            });
        });
    }
}

// 修改现有函数以支持分页
function filterPoliciesByGroup(groupId) {
    // 重置分页
    resetPagination();
    
    const policies = getPoliciesFromLocalStorage();
    let filteredPolicies = [];
    
    // 定义策略类型到分组的映射
    const typeToGroupMap = {
        '数据泄露检测': '数据泄露防护',
        '敏感信息识别': '数据泄露防护',
        '异常登录检测': '异常访问检测',
        '权限滥用检测': '异常访问检测'
    };
    
    // 根据groupId过滤策略
    if (!groupId || groupId === 'all') {
        // 显示所有策略
        filteredPolicies = policies;
    } else if (typeToGroupMap[groupId]) {
        // 如果groupId是策略类型，先转换为对应的分组名
        const actualGroupId = typeToGroupMap[groupId];
        filteredPolicies = policies.filter(policy => typeToGroupMap[policy.type] === actualGroupId);
    } else {
        // 直接根据策略类型对应的分组过滤
        filteredPolicies = policies.filter(policy => typeToGroupMap[policy.type] === groupId);
    }
    
    // 如果有搜索关键词，应用搜索过滤
    const searchInput = document.getElementById('search-input');
    if (searchInput && searchInput.value.trim()) {
        const searchKeyword = searchInput.value.trim().toLowerCase();
        filteredPolicies = filteredPolicies.filter(policy => 
            policy.name.toLowerCase().includes(searchKeyword) ||
            policy.type.toLowerCase().includes(searchKeyword)
        );
    }
    
    // 应用排序
    if (currentSortColumn) {
        filteredPolicies.sort((a, b) => {
            let aValue = a[currentSortColumn];
            let bValue = b[currentSortColumn];
            
            // 字符串比较
            if (typeof aValue === 'string') {
                aValue = aValue.toLowerCase();
                bValue = bValue.toLowerCase();
            }
            
            if (currentSortDirection === 'asc') {
                return aValue > bValue ? 1 : -1;
            } else {
                return aValue < bValue ? 1 : -1;
            }
        });
    }
    
    // 渲染过滤后的策略列表
    renderPolicyList(filteredPolicies);
    
    // 更新总数显示
    const totalCountElement = document.querySelector('.text-text-secondary.text-sm');
    if (totalCountElement) {
        totalCountElement.textContent = `共 ${filteredPolicies.length} 条策略`;
    }
    
    // 高亮选中的分组
    document.querySelectorAll('.policy-group-item').forEach(item => {
        if (item.dataset.id === groupId || (!groupId && item.dataset.id === 'all')) {
            item.classList.add('bg-primary/10', 'text-primary');
        } else {
            item.classList.remove('bg-primary/10', 'text-primary');
        }
    });
}

// 更新策略名称
function updatePolicyName(policyId, newName, container) {
    // 从localStorage获取当前策略数据
    const policies = getPoliciesFromLocalStorage();
    const policyIndex = policies.findIndex(p => p.id === policyId);
    
    if (policyIndex !== -1) {
        // 更新策略名称
        policies[policyIndex].name = newName;
        policies[policyIndex].lastModified = getCurrentTime();
        
        // 保存回localStorage
        savePoliciesToLocalStorage(policies);
        
        // 恢复显示
        restorePolicyNameDisplay(container, newName, policyId);
        
        // 更新总数显示
        updateTotalCount();
        
        // 重置分页并应用当前过滤和排序
        resetPagination();
        
        // 获取当前搜索条件
        const searchInput = document.querySelector('.search-input');
        const searchTerm = searchInput ? searchInput.value.trim() : '';
        
        // 应用搜索过滤
        const filteredPolicies = filterPolicies(searchTerm);
        
        // 应用排序
        if (currentSortColumn) {
            sortPolicies(currentSortColumn);
        } else {
            // 如果没有排序条件，直接渲染
            currentPolicies = filteredPolicies;
            renderPolicyList(filteredPolicies);
        }
        
        // 显示成功提示
        showNotification('策略名称更新成功', 'success');
    }
}

// 恢复策略名称显示
function restorePolicyNameDisplay(container, name, policyId) {
    container.innerHTML = `
        <span class="font-medium text-text-primary policy-name-text">${name}</span>
        <button class="edit-name-btn ml-2 text-text-secondary hover:text-primary transition-colors duration-300 opacity-0 hover:opacity-100" title="编辑名称" data-id="${policyId}">
            <i class="fa fa-pencil text-xs"></i>
        </button>
    `;
    
    // 重新绑定编辑按钮事件
    bindPolicyRowEvents();
    
    // 移除事件监听
    document.removeEventListener('click', handleClickOutsideEditName);
}

// 获取当前时间
function getCurrentTime() {
    const now = new Date();
    return now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 更新策略总数显示
function updateTotalCount() {
    const policies = JSON.parse(localStorage.getItem('policies')) || [];
    const totalCountElement = document.getElementById('total-count');
    if (totalCountElement) {
        totalCountElement.textContent = policies.length;
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 p-3 rounded-lg shadow-lg z-50 transition-all duration-500 transform translate-x-full`;
    
    // 设置样式
    if (type === 'success') {
        notification.classList.add('bg-green-100', 'text-green-800', 'border-l-4', 'border-green-500');
    } else if (type === 'error') {
        notification.classList.add('bg-red-100', 'text-red-800', 'border-l-4', 'border-red-500');
    } else {
        notification.classList.add('bg-blue-100', 'text-blue-800', 'border-l-4', 'border-blue-500');
    }
    
    notification.textContent = message;
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
        notification.classList.add('translate-x-0');
    }, 10);
    
    // 3秒后隐藏通知
    setTimeout(() => {
        notification.classList.remove('translate-x-0');
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 500);
    }, 3000);
    }

// 编辑策略
function editPolicy(policyId) {
    // 选择策略
    selectPolicy(policyId);
    
    // 确保策略向导已初始化
    ensureWizardInitialized();
    
    // 打开策略向导并传入策略ID以进入编辑模式
    openPolicyWizard(policyId);
}

// 复制策略
function copyPolicy(policyId) {
    const policies = getPoliciesFromLocalStorage();
    const policyToCopy = policies.find(p => p.id === policyId);
    
    if (!policyToCopy) return;
    
    // 创建副本
    const newPolicy = JSON.parse(JSON.stringify(policyToCopy));
    newPolicy.id = Date.now(); // 使用时间戳作为新ID
    newPolicy.name = `${newPolicy.name} (副本)`;
    newPolicy.lastModified = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    }).replace(/\//g, '-');
    newPolicy.status = 'disabled'; // 新复制的策略默认禁用
    
    // 添加到列表
    policies.push(newPolicy);
    savePoliciesToLocalStorage(policies);
    
    // 重置分页并应用当前过滤和排序
    resetPagination();
    
    // 获取当前搜索条件
    const searchInput = document.querySelector('.search-input');
    const searchTerm = searchInput ? searchInput.value.trim() : '';
    
    // 应用搜索过滤
    const filteredPolicies = filterPolicies(searchTerm);
    
    // 应用排序
    if (currentSortColumn) {
        sortPolicies(currentSortColumn);
    } else {
        // 如果没有排序条件，直接渲染
        currentPolicies = filteredPolicies;
        renderPolicyList(filteredPolicies);
    }
    
    // 显示成功提示
    showNotification('策略复制成功', 'success');
}

// 删除策略
function deletePolicy(policyId) {
    if (!confirm('确定要删除这条策略吗？此操作不可撤销。')) {
        return;
    }
    
    let policies = getPoliciesFromLocalStorage();
    policies = policies.filter(p => p.id !== policyId);
    
    savePoliciesToLocalStorage(policies);
    
    // 重置分页并应用当前过滤和排序
    resetPagination();
    
    // 获取当前搜索条件
    const searchInput = document.querySelector('.search-input');
    const searchTerm = searchInput ? searchInput.value.trim() : '';
    
    // 应用搜索过滤
    const filteredPolicies = filterPolicies(searchTerm);
    
    // 应用排序
    if (currentSortColumn) {
        sortPolicies(currentSortColumn);
    } else {
        // 如果没有排序条件，直接渲染
        currentPolicies = filteredPolicies;
        renderPolicyList(filteredPolicies);
    }
    
    // 如果删除的是当前选中的策略，清空详情面板
    if (currentSelectedPolicy === policyId) {
        currentSelectedPolicy = null;
        const detailContainer = document.querySelector('.policy-detail');
        if (detailContainer) {
            detailContainer.innerHTML = `
                <div class="text-center py-8 text-text-secondary">
                    <div class="mb-4 animate-float">
                        <i class="fa fa-info-circle text-6xl text-primary/20"></i>
                    </div>
                    <p>请选择一条策略查看详细信息</p>
                </div>
            `;
        }
    }
    
    // 显示成功提示
    showNotification('策略删除成功', 'success');
}

// 切换策略状态
function togglePolicyStatus(policyId) {
    const policies = getPoliciesFromLocalStorage();
    const policy = policies.find(p => p.id === policyId);
    
    if (!policy) return;
    
    // 切换状态
    policy.status = policy.status === 'enabled' ? 'disabled' : 'enabled';
    policy.lastModified = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    }).replace(/\//g, '-');
    
    savePoliciesToLocalStorage(policies);
    
    // 重置分页并应用当前过滤和排序
    resetPagination();
    
    // 获取当前搜索条件
    const searchInput = document.querySelector('.search-input');
    const searchTerm = searchInput ? searchInput.value.trim() : '';
    
    // 应用搜索过滤
    const filteredPolicies = filterPolicies(searchTerm);
    
    // 应用排序
    if (currentSortColumn) {
        sortPolicies(currentSortColumn);
    } else {
        // 如果没有排序条件，直接渲染
        currentPolicies = filteredPolicies;
        renderPolicyList(filteredPolicies);
    }
    
    // 如果是当前选中的策略，更新详情
    if (currentSelectedPolicy === policyId) {
        showPolicyDetails(policyId);
    }
    
    // 显示成功提示
    showNotification(`策略已${policy.status === 'enabled' ? '启用' : '禁用'}`, 'success');
}

// 更新批量操作状态
function updateBatchActions() {
    const checkedBoxes = document.querySelectorAll('.policy-checkbox:checked');
    const hasChecked = checkedBoxes.length > 0;
    
    // 启用/禁用批量操作按钮
    const batchDeleteBtn = document.getElementById('batch-delete-btn');
    const batchExportBtn = document.getElementById('batch-export-btn');
    
    if (batchDeleteBtn) {
        batchDeleteBtn.disabled = !hasChecked;
        batchDeleteBtn.classList.toggle('opacity-50', !hasChecked);
    }
    
    if (batchExportBtn) {
        batchExportBtn.disabled = !hasChecked;
        batchExportBtn.classList.toggle('opacity-50', !hasChecked);
    }
    
    // 更新已选择计数
    const selectedCountSpan = document.getElementById('selected-count');
    if (selectedCountSpan) {
        selectedCountSpan.textContent = checkedBoxes.length;
    }
}

// 打开批量确认模态框
function openBatchConfirmModal() {
    const batchConfirmModal = document.getElementById('batch-confirm-modal');
    if (batchConfirmModal) {
        // 更新选中计数
        const checkedBoxes = document.querySelectorAll('.policy-checkbox:checked');
        const selectedCountSpan = document.getElementById('selected-count');
        if (selectedCountSpan) {
            selectedCountSpan.textContent = checkedBoxes.length;
        }
        
        // 显示模态框
        batchConfirmModal.classList.remove('hidden');
        
        // 添加动画效果
        batchConfirmModal.classList.add('animate-fadeIn');
        setTimeout(() => {
            const modalContent = batchConfirmModal.querySelector('.bg-white');
            if (modalContent) {
                modalContent.classList.add('animate-scaleIn');
            }
        }, 10);
    }
}

// 关闭批量确认模态框
function closeBatchConfirmModal() {
    const batchConfirmModal = document.getElementById('batch-confirm-modal');
    if (batchConfirmModal) {
        const modalContent = batchConfirmModal.querySelector('.bg-white');
        if (modalContent) {
            modalContent.classList.remove('animate-scaleIn');
            modalContent.classList.add('animate-scaleOut');
        }
        
        setTimeout(() => {
            batchConfirmModal.classList.add('hidden');
            batchConfirmModal.classList.remove('animate-fadeIn');
            if (modalContent) {
                modalContent.classList.remove('animate-scaleOut');
            }
        }, 300);
    }
}

// 批量删除策略
function batchDeletePolicies() {
    const checkedBoxes = document.querySelectorAll('.policy-checkbox:checked');
    if (checkedBoxes.length === 0) {
        return;
    }
    
    // 获取选中的策略ID
    const policyIds = Array.from(checkedBoxes).map(box => parseInt(box.dataset.id));
    
    try {
        // 获取所有策略并删除选中项
        let policies = getPoliciesFromLocalStorage();
        policies = policies.filter(p => !policyIds.includes(p.id));
        savePoliciesToLocalStorage(policies);
        
        // 重置分页并应用当前过滤和排序
        resetPagination();
        
        // 获取当前搜索条件
        const searchInput = document.querySelector('.search-input');
        const searchTerm = searchInput ? searchInput.value.trim() : '';
        
        // 应用搜索过滤
        const filteredPolicies = filterPolicies(searchTerm);
        
        // 应用排序
        if (currentSortColumn) {
            sortPolicies(currentSortColumn);
        } else {
            // 如果没有排序条件，直接渲染
            currentPolicies = filteredPolicies;
            renderPolicyList(filteredPolicies);
        }
        
        // 关闭模态框
        closeBatchConfirmModal();
        
        // 显示成功通知
        showNotification(`成功删除 ${policyIds.length} 条策略`, 'success');
        
        // 如果当前正在查看的策略被删除，清空详情面板
        if (policyIds.includes(currentSelectedPolicy)) {
            currentSelectedPolicy = null;
            const detailContainer = document.querySelector('.policy-detail');
            if (detailContainer) {
                detailContainer.innerHTML = `
                    <div class="text-center py-8 text-text-secondary">
                        <div class="mb-4 animate-float">
                            <i class="fa fa-info-circle text-6xl text-primary/20"></i>
                        </div>
                        <p>请选择一条策略查看详细信息</p>
                    </div>
                `;
            }
        }
        
        // 更新全选复选框状态
        const selectAllCheckbox = document.querySelector('input[type="checkbox"]:not(.policy-checkbox)');
        if (selectAllCheckbox) {
            selectAllCheckbox.checked = false;
        }
        
    } catch (error) {
        console.error('批量删除策略失败:', error);
        showNotification('批量删除策略失败，请重试', 'error');
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 px-4 py-3 rounded-lg shadow-card z-50 smooth-transition transform translate-x-full opacity-0`;
    
    // 设置样式
    if (type === 'success') {
        notification.classList.add('bg-green-100', 'text-green-800', 'border-l-4', 'border-green-500');
    } else if (type === 'error') {
        notification.classList.add('bg-red-100', 'text-red-800', 'border-l-4', 'border-red-500');
    } else {
        notification.classList.add('bg-blue-100', 'text-blue-800', 'border-l-4', 'border-blue-500');
    }
    
    // 设置内容
    notification.innerHTML = `
        <div class="flex items-center justify-between">
            <div class="flex items-center">
                <i class="fa fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'} mr-2"></i>
                <span>${message}</span>
            </div>
            <button class="ml-4 text-gray-500 hover:text-gray-700 transition-colors close-notification">
                <i class="fa fa-times"></i>
            </button>
        </div>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.classList.remove('translate-x-full', 'opacity-0');
        notification.classList.add('translate-x-0', 'opacity-100');
    }, 10);
    
    // 关闭按钮事件
    const closeBtn = notification.querySelector('.close-notification');
    if (closeBtn) {
        closeBtn.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            hideNotification(notification);
        });
    }
    
    // 自动消失
    const timeoutId = setTimeout(() => {
        hideNotification(notification);
    }, 4000);
    
    // 点击通知立即关闭
    notification.addEventListener('click', () => {
        clearTimeout(timeoutId);
        hideNotification(notification);
    });
}

// 隐藏通知
function hideNotification(notification) {
    notification.classList.remove('translate-x-0', 'opacity-100');
    notification.classList.add('translate-x-full', 'opacity-0');
    setTimeout(() => {
        if (document.body.contains(notification)) {
            document.body.removeChild(notification);
        }
    }, 300);
}

// 绑定事件监听器
function bindEventListeners() {
    // 获取详情面板相关元素
    const togglePanelBtn = document.querySelector('#toggle-detail-btn');
    const sidebarCollapsed = false;
    const detailPanelCollapsed = false;
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    const mobileDetailBtn = document.getElementById('mobile-detail-btn');
    
    // 切换详情面板按钮
    if (togglePanelBtn) {
        togglePanelBtn.addEventListener('click', toggleDetailPanel);
    }
    
    // 新增策略按钮
    const addPolicyBtn = document.querySelector('button:has(.fa-plus)');
    if (addPolicyBtn) {
        addPolicyBtn.addEventListener('click', () => {
            openPolicyWizard();
        });
    }
    
    // 导入按钮
    const importBtn = document.querySelector('button:has(.fa-upload)');
    if (importBtn) {
        importBtn.addEventListener('click', () => {
            alert('导入功能待实现');
        });
    }
    
    // 导出按钮
    const exportBtn = document.querySelector('button:has(.fa-download)');
    if (exportBtn) {
        exportBtn.addEventListener('click', () => {
            const checkedBoxes = document.querySelectorAll('.policy-checkbox:checked');
            if (checkedBoxes.length === 0) {
                alert('请先选择要导出的策略');
                return;
            }
            
            const policyIds = Array.from(checkedBoxes).map(box => parseInt(box.dataset.id));
            exportPolicies(policyIds);
        });
    }
    
    // 侧边栏折叠按钮
    const toggleSidebarBtn = document.getElementById('toggle-sidebar-btn');
    if (toggleSidebarBtn) {
        // 临时移除toggleSidebar调用
        toggleSidebarBtn.addEventListener('click', function() {
            console.log('Toggle sidebar clicked');
        });
    }
    
    // 移动设备按钮事件
    if (mobileMenuBtn) {
        mobileMenuBtn.addEventListener('click', function() {
            console.log('Mobile menu button clicked');
        });
    }
    
    if (mobileDetailBtn) {
        mobileDetailBtn.addEventListener('click', function() {
            console.log('Mobile detail button clicked');
        });
    }
    
    // 搜索框
    const searchInput = document.querySelector('input[placeholder="搜索策略..."]');
    if (searchInput) {
        searchInput.addEventListener('input', (e) => {
            const searchTerm = e.target.value.toLowerCase();
            filterPolicies(searchTerm);
        });
    }
    
    // 全选复选框
    const selectAllCheckbox = document.querySelector('input[type="checkbox"]:not(.policy-checkbox)');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', (e) => {
            const isChecked = e.target.checked;
            document.querySelectorAll('.policy-checkbox').forEach(checkbox => {
                checkbox.checked = isChecked;
            });
            updateBatchActions();
        });
    }
    
    // 批量操作按钮
    const batchActionsBtn = document.getElementById('batch-actions-btn');
    if (batchActionsBtn) {
        batchActionsBtn.addEventListener('click', () => {
            const checkedBoxes = document.querySelectorAll('.policy-checkbox:checked');
            if (checkedBoxes.length === 0) {
                alert('请先选择要操作的策略');
                return;
            }
            
            // 显示批量操作菜单或直接进行批量删除确认
            // 这里我们直接显示批量删除确认模态框
            openBatchConfirmModal();
        });
    }
    
    // 取消批量操作按钮
    const cancelBatchBtn = document.getElementById('cancel-batch-btn');
    if (cancelBatchBtn) {
        cancelBatchBtn.addEventListener('click', () => {
            closeBatchConfirmModal();
        });
    }
    
    // 策略分组点击事件
    const policyGroups = document.querySelectorAll('.policy-group-item');
    policyGroups.forEach(group => {
        group.addEventListener('click', () => {
            // 移除所有分组的选中状态
            policyGroups.forEach(g => {
                g.classList.remove('bg-primary/10');
                g.classList.remove('active-indicator');
            });
            
            // 添加当前分组的选中状态
            group.classList.add('bg-primary/10');
            group.classList.add('active-indicator');
            
            // 获取分组ID
            const groupId = group.dataset.groupId;
            
            // 过滤并显示相应的策略
            filterPoliciesByGroup(groupId);
            
            // 切换分组的展开/折叠状态（跳过"所有策略"分组）
            if (groupId !== 'all') {
                const folderIcon = group.querySelector('i.fa-folder, i.fa-folder-open');
                if (folderIcon) {
                    // 添加过渡动画类
                    folderIcon.classList.add('transition-all');
                    folderIcon.classList.add('duration-300');
                    
                    if (folderIcon.classList.contains('fa-folder')) {
                        // 展开分组
                        folderIcon.classList.remove('fa-folder');
                        folderIcon.classList.add('fa-folder-open');
                        folderIcon.classList.remove('text-primary/70');
                        folderIcon.classList.add('text-primary');
                    } else if (folderIcon.classList.contains('fa-folder-open')) {
                        // 折叠分组
                        folderIcon.classList.remove('fa-folder-open');
                        folderIcon.classList.add('fa-folder');
                        folderIcon.classList.remove('text-primary');
                        folderIcon.classList.add('text-primary/70');
                    }
                }
            }
        });
    });
    
    // 展开全部按钮
    const expandAllBtn = document.getElementById('expand-all-btn');
    if (expandAllBtn) {
        expandAllBtn.addEventListener('click', () => {
            expandAllGroups();
        });
    }
    
    // 折叠全部按钮
    const collapseAllBtn = document.getElementById('collapse-all-btn');
    if (collapseAllBtn) {
        collapseAllBtn.addEventListener('click', () => {
            collapseAllGroups();
        });
    }
    
    // 展开所有分组
    function expandAllGroups() {
        const policyGroups = document.querySelectorAll('.policy-group-item');
        policyGroups.forEach(group => {
            // 更改文件夹图标为展开状态
            const folderIcon = group.querySelector('i.fa-folder, i.fa-folder-open');
            if (folderIcon) {
                folderIcon.classList.remove('fa-folder');
                folderIcon.classList.add('fa-folder-open');
                folderIcon.classList.remove('text-primary/70');
                folderIcon.classList.add('text-primary');
            }
        });
    }
    
    // 折叠所有分组
    function collapseAllGroups() {
        const policyGroups = document.querySelectorAll('.policy-group-item');
        policyGroups.forEach(group => {
            // 跳过"所有策略"分组，保持其始终展开
            if (group.dataset.groupId !== 'all') {
                // 更改文件夹图标为折叠状态
                const folderIcon = group.querySelector('i.fa-folder, i.fa-folder-open');
                if (folderIcon) {
                    folderIcon.classList.remove('fa-folder-open');
                    folderIcon.classList.add('fa-folder');
                    folderIcon.classList.remove('text-primary');
                    folderIcon.classList.add('text-primary/70');
                }
            }
        });
    }
    
    // 根据分组过滤策略
    function filterPoliciesByGroup(groupId) {
        // 使用data.js中的函数获取策略数据
        const policies = getPoliciesFromLocalStorage();
        let filteredPolicies = policies;
        
        // 如果不是'所有策略'分组，则进行过滤
        if (groupId !== 'all') {
            // 根据分组ID过滤策略
            filteredPolicies = policies.filter(policy => {
                // 检查策略对象是否有group属性直接对应分组ID
                if (policy.group === groupId) {
                    return true;
                }
                
                // 根据策略类型映射到对应的分组
                const typeToGroupMap = {
                    '数据泄露防护': 'data-leakage',
                    '异常访问检测': 'abnormal-access',
                    '合规性监控': 'compliance'
                };
                
                // 确保policy.type存在且在映射中
                return policy.type && typeToGroupMap[policy.type] === groupId;
            });
        }
        
        // 渲染过滤后的策略列表
        renderPolicyList(filteredPolicies);
        
        // 更新总数显示
        const totalCountElement = document.getElementById('total-count');
        if (totalCountElement) {
            totalCountElement.textContent = filteredPolicies.length;
        }
        
        // 重置搜索框
        const searchInput = document.querySelector('input[placeholder="搜索策略..."]');
        if (searchInput) {
            searchInput.value = '';
        }
    }
    
    // 确认批量删除按钮
    const confirmBatchBtn = document.getElementById('confirm-batch-btn');
    if (confirmBatchBtn) {
        confirmBatchBtn.addEventListener('click', () => {
            batchDeletePolicies();
        });
    }
}

// 过滤策略
function filterPolicies(searchTerm) {
    // 重置分页
    resetPagination();
    
    const policies = getPoliciesFromLocalStorage();
    const filteredPolicies = policies.filter(policy => 
        policy.name.toLowerCase().includes(searchTerm) ||
        policy.type.toLowerCase().includes(searchTerm) ||
        policy.description.toLowerCase().includes(searchTerm) ||
        policy.group.toLowerCase().includes(searchTerm) ||
        policy.protocols.some(protocol => protocol.toLowerCase().includes(searchTerm))
    );
    
    // 应用排序
    if (currentSortColumn) {
        switch(currentSortColumn) {
            case '策略名称':
                filteredPolicies.sort((a, b) => {
                    const compare = a.name.localeCompare(b.name);
                    return currentSortDirection === 'asc' ? compare : -compare;
                });
                break;
            case '策略类型':
                filteredPolicies.sort((a, b) => {
                    const compare = a.type.localeCompare(b.type);
                    return currentSortDirection === 'asc' ? compare : -compare;
                });
                break;
            case '优先级':
                filteredPolicies.sort((a, b) => {
                    const compare = a.priority - b.priority;
                    return currentSortDirection === 'asc' ? compare : -compare;
                });
                break;
            case '状态':
                filteredPolicies.sort((a, b) => {
                    let compare = 0;
                    if (a.status === 'enabled' && b.status !== 'enabled') compare = -1;
                    if (a.status !== 'enabled' && b.status === 'enabled') compare = 1;
                    return currentSortDirection === 'asc' ? compare : -compare;
                });
                break;
            case '最后修改时间':
                filteredPolicies.sort((a, b) => {
                    const compare = new Date(a.lastModified) - new Date(b.lastModified);
                    return currentSortDirection === 'asc' ? compare : -compare;
                });
                break;
        }
    }
    
    renderPolicyList(filteredPolicies);
}

// 导出策略
function exportPolicies(policyIds) {
    const policies = getPoliciesFromLocalStorage();
    const policiesToExport = policies.filter(p => policyIds.includes(p.id));
    
    // 创建JSON字符串
    const jsonData = JSON.stringify(policiesToExport, null, 2);
    
    // 创建Blob对象
    const blob = new Blob([jsonData], { type: 'application/json' });
    
    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `policies_export_${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    
    // 触发下载
    a.click();
    
    // 清理
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    showNotification(`成功导出 ${policiesToExport.length} 条策略`, 'success');
}

// 初始化交互
function initInteractions() {
    // 为排序表头添加点击事件
    document.querySelectorAll('.font-medium.cursor-pointer').forEach(header => {
        header.addEventListener('click', () => {
            const column = header.querySelector('span').textContent;
            sortPolicies(column);
        });
    });
    
    // 初始化搜索框事件
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase().trim();
            filterPolicies(searchTerm);
        });
    }
}

// 排序策略
function sortPolicies(column) {
    // 切换排序方向
    if (currentSortColumn === column) {
        currentSortDirection = currentSortDirection === 'asc' ? 'desc' : 'asc';
    } else {
        currentSortColumn = column;
        currentSortDirection = 'asc';
        // 优先级默认降序
        if (column === '优先级' || column === '最后修改时间') {
            currentSortDirection = 'desc';
        }
    }
    
    // 重置分页
    resetPagination();
    
    // 更新排序图标
    updateSortIcons(column);
    
    // 获取当前过滤的策略列表
    let policies = [];
    if (currentPolicies.length > 0) {
        // 使用当前已经过滤的策略列表
        policies = [...currentPolicies];
    } else {
        policies = getPoliciesFromLocalStorage();
    }
    
    switch(column) {
        case '策略名称':
            policies.sort((a, b) => {
                const compare = a.name.localeCompare(b.name);
                return currentSortDirection === 'asc' ? compare : -compare;
            });
            break;
        case '策略类型':
            policies.sort((a, b) => {
                const compare = a.type.localeCompare(b.type);
                return currentSortDirection === 'asc' ? compare : -compare;
            });
            break;
        case '优先级':
            policies.sort((a, b) => {
                const compare = a.priority - b.priority;
                return currentSortDirection === 'asc' ? compare : -compare;
            });
            break;
        case '状态':
            policies.sort((a, b) => {
                let compare = 0;
                if (a.status === 'enabled' && b.status !== 'enabled') compare = -1;
                if (a.status !== 'enabled' && b.status === 'enabled') compare = 1;
                return currentSortDirection === 'asc' ? compare : -compare;
            });
            break;
        case '最后修改时间':
            policies.sort((a, b) => {
                const compare = new Date(a.lastModified) - new Date(b.lastModified);
                return currentSortDirection === 'asc' ? compare : -compare;
            });
            break;
    }
    
    renderPolicyList(policies);
}

// 更新排序图标
function updateSortIcons(column) {
    // 移除所有排序图标
    document.querySelectorAll('.font-medium.cursor-pointer').forEach(header => {
        const existingIcon = header.querySelector('.fa-sort, .fa-sort-up, .fa-sort-down');
        if (existingIcon) {
            existingIcon.remove();
        }
    });
    
    // 添加当前列的排序图标
    const currentHeader = Array.from(document.querySelectorAll('.font-medium.cursor-pointer'))
        .find(header => header.querySelector('span').textContent === column);
    
    if (currentHeader) {
        const icon = document.createElement('i');
        icon.className = `fa ml-1 ${currentSortDirection === 'asc' ? 'fa-sort-up' : 'fa-sort-down'}`;
        currentHeader.appendChild(icon);
    }
}

// 当DOM加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
} else {
    init();
}

// 添加到调试控制台的辅助函数，便于手动测试
window.debugTools = {
    // 清除所有数据并重新初始化
    resetApp: function() {
        localStorage.clear();
        location.reload();
    },
    
    // 运行数据验证
    validateData: function() {
        return runDataValidationTests();
    },
    
    // 生成测试数据
    generateTestData: function() {
        localStorage.clear();
        initializeDefaultData();
    },
    
    // 导出所有数据
    exportAllData: function() {
        const data = {
            policies: getPoliciesFromLocalStorage(),
            groups: JSON.parse(localStorage.getItem('policyGroups') || '[]'),
            exportTime: new Date().toISOString()
        };
        
        const jsonData = JSON.stringify(data, null, 2);
        const blob = new Blob([jsonData], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `all_data_export_${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }
};

console.log('=== 数据安全监测系统初始化完成 ===');
console.log('调试工具已加载，可使用 window.debugTools 访问');
console.log('可用功能:');
console.log('- debugTools.resetApp() - 重置应用');
console.log('- debugTools.validateData() - 验证数据');
console.log('- debugTools.generateTestData() - 生成测试数据');
console.log('- debugTools.exportAllData() - 导出所有数据');

// 策略创建向导相关变量
let currentStep = 1;
const totalSteps = 4;
let policyFormData = {};
let isEditMode = false;
let editPolicyId = null;

// 打开策略向导
function openPolicyWizard(policyId = null) {
    // 重置表单数据
    policyFormData = {};
    currentStep = 1;
    
    // 重置模式
    isEditMode = policyId !== null;
    editPolicyId = policyId;
    
    // 更新标题
    const wizardTitle = document.querySelector('#policy-wizard-modal h2');
    if (wizardTitle) {
        wizardTitle.textContent = isEditMode ? '编辑策略' : '创建新策略';
    }
    
    // 如果是编辑模式，加载策略数据
    if (isEditMode) {
        const policies = getPoliciesFromLocalStorage();
        const policy = policies.find(p => p.id === policyId);
        if (policy) {
            loadPolicyDataForEdit(policy);
        }
    }
    
    // 显示模态框
    const modal = document.getElementById('policy-wizard-modal');
    if (modal) {
        // 重置动画类
        const modalContent = modal.querySelector('.bg-white');
        modalContent.classList.remove('animate-scaleOut', 'animate-fadeIn');
        
        // 显示背景并添加淡入效果
        modal.classList.remove('hidden');
        modal.classList.add('animate-fadeIn');
        
        // 添加内容缩放动画
        setTimeout(() => {
            modalContent.classList.add('animate-scaleIn');
        }, 10);
    }
    
    // 更新步骤状态
    updateWizardStepUI();
}

// 关闭策略向导
function closePolicyWizard() {
    const modal = document.getElementById('policy-wizard-modal');
    if (modal) {
        const modalContent = modal.querySelector('.bg-white');
        
        // 添加内容缩放消失动画
        modalContent.classList.remove('animate-scaleIn');
        modalContent.classList.add('animate-scaleOut');
        
        // 动画完成后隐藏模态框
        setTimeout(() => {
            modal.classList.remove('animate-fadeIn');
            modal.classList.add('hidden');
            modalContent.classList.remove('animate-scaleOut');
        }, 250);
    }
    
    // 重置步骤
    currentStep = 1;
    isEditMode = false;
    editPolicyId = null;
    
    // 清空表单数据
    policyFormData = {};
}

// 加载策略数据（编辑模式）
function loadPolicyDataForEdit(policy) {
    policyFormData = { ...policy };
    
    // 填充步骤1的表单字段 - 基础信息
    const nameInput = document.querySelector('#wizard-content input[placeholder="请输入策略名称"]');
    const typeSelect = document.querySelector('#wizard-content select[name="policy-type"]');
    const groupSelect = document.querySelector('#wizard-content select[name="policy-group"]');
    const prioritySlider = document.getElementById('priority-slider');
    const descriptionTextarea = document.querySelector('#wizard-content textarea[placeholder="请输入策略描述"]');
    
    if (nameInput) nameInput.value = policy.name || '';
    if (typeSelect) typeSelect.value = policy.type || '';
    if (groupSelect) groupSelect.value = policy.group || '';
    if (prioritySlider) prioritySlider.value = policy.priority || 5;
    if (descriptionTextarea) descriptionTextarea.value = policy.description || '';
    
    // 填充步骤2的表单字段 - 检测规则
    const rulesContainer = document.getElementById('rules-container');
    if (rulesContainer && policy.rules && policy.rules.length > 0) {
        // 清空现有规则
        rulesContainer.innerHTML = '';
        
        // 添加策略中的规则
        policy.rules.forEach((rule, index) => {
            // 创建临时元素以安全地解析HTML
            const tempElement = document.createElement('div');
            
            // 规则HTML模板
            const ruleHTML = `
                <div class="bg-bg-secondary p-4 rounded-lg border border-border/10 animate-fadeIn">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
                        <div>
                            <label class="block text-xs text-text-secondary mb-1">规则类型</label>
                            <select class="w-full px-2 py-1.5 text-sm border border-border/40 rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary">
                                <option value="regex" ${rule.type === 'regex' ? 'selected' : ''}>正则表达式</option>
                                <option value="file-size" ${rule.type === 'file-size' ? 'selected' : ''}>文件大小</option>
                                <option value="file-count" ${rule.type === 'file-count' ? 'selected' : ''}>文件数量</option>
                                <option value="rate-limit" ${rule.type === 'rate-limit' ? 'selected' : ''}>访问频率</option>
                                <option value="encryption" ${rule.type === 'encryption' ? 'selected' : ''}>加密要求</option>
                                <option value="tls-version" ${rule.type === 'tls-version' ? 'selected' : ''}>TLS版本</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs text-text-secondary mb-1">规则描述</label>
                            <input type="text" class="w-full px-2 py-1.5 text-sm border border-border/40 rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary" placeholder="简要描述此规则" value="${rule.description || ''}">
                        </div>
                    </div>
                    <div class="rule-params space-y-3">
                        <div>
                            <label class="block text-xs text-text-secondary mb-1">正则表达式模式</label>
                            <input type="text" class="w-full px-2 py-1.5 text-sm border border-border/40 rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary" placeholder="如: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}$" value="${rule.pattern || ''}">
                        </div>
                        <div class="flex items-center gap-2">
                            <input type="checkbox" id="case-sensitive-${index + 1}" class="rounded text-primary focus:ring-primary" ${rule.caseSensitive ? 'checked' : ''}>
                            <label for="case-sensitive-${index + 1}" class="text-xs text-text-secondary">区分大小写</label>
                        </div>
                    </div>
                    <div class="flex justify-between items-center mt-3">
                        <div class="text-xs text-text-tertiary">规则 #${index + 1}</div>
                        <button class="text-danger hover:text-danger/80 transition-colors remove-rule-btn" ${policy.rules.length === 1 ? 'disabled' : ''}>
                            <i class="fa fa-trash"></i>
                        </button>
                    </div>
                </div>
            `;
            
            tempElement.innerHTML = ruleHTML;
            const ruleElement = tempElement.firstElementChild;
            rulesContainer.appendChild(ruleElement);
            
            // 添加删除按钮事件
            const deleteBtn = ruleElement.querySelector('.remove-rule-btn');
            if (deleteBtn && policy.rules.length > 1) {
                deleteBtn.addEventListener('click', function() {
                    ruleElement.classList.add('animate-fadeOut');
                    setTimeout(() => {
                        rulesContainer.removeChild(ruleElement);
                        updateRuleNumbers();
                    }, 300);
                });
            }
        });
        
        // 设置逻辑关系
        const anyMatchCheckbox = document.getElementById('any-match');
        const allMatchCheckbox = document.getElementById('all-match');
        if (policy.matchLogic === 'any' && anyMatchCheckbox) {
            anyMatchCheckbox.checked = true;
            if (allMatchCheckbox) allMatchCheckbox.checked = false;
        } else if (policy.matchLogic === 'all' && allMatchCheckbox) {
            allMatchCheckbox.checked = true;
            if (anyMatchCheckbox) anyMatchCheckbox.checked = false;
        }
    }
    
    // 填充步骤3的表单字段 - 检测通道
    if (policy.protocols && policy.protocols.length > 0) {
        policy.protocols.forEach(protocol => {
            const protocolCheckbox = document.querySelector(`input[name="protocol"][value="${protocol}"]`);
            if (protocolCheckbox) protocolCheckbox.checked = true;
        });
    }
    
    // 填充高级配置
    if (policy.advancedConfig) {
        const thresholdInput = document.querySelector('.wizard-step-3 input[type="number"]');
        const periodSelect = document.querySelector('.wizard-step-3 select');
        
        if (thresholdInput && policy.advancedConfig.threshold) thresholdInput.value = policy.advancedConfig.threshold;
        if (periodSelect && policy.advancedConfig.period) periodSelect.value = policy.advancedConfig.period;
    }
    
    // 填充步骤4的表单字段 - 检测动作
    if (policy.actions) {
        // 设置命中管控
        const controlAction = document.querySelector(`input[name="control-action"][value="${policy.actions.control || 'alert'}"]`);
        if (controlAction) controlAction.checked = true;
        
        // 设置通知通道
        if (policy.actions.notification && policy.actions.notification.length > 0) {
            policy.actions.notification.forEach(channel => {
                const notificationCheckbox = document.querySelector(`input[name="notification"][value="${channel}"]`);
                if (notificationCheckbox) notificationCheckbox.checked = true;
            });
        }
        
        // 设置通知时机
        if (policy.actions.notificationType && policy.actions.notificationType.length > 0) {
            const notificationType = document.querySelector(`input[name="notification-type"][value="${policy.actions.notificationType[0] || 'real-time'}"]`);
            if (notificationType) notificationType.checked = true;
        }
    }
}

// 初始化策略创建向导
function initPolicyWizard() {
    // 新增策略按钮事件已在bindEventListeners中绑定
    
    // 关闭向导按钮事件
    const closeWizardBtn = document.getElementById('close-wizard-btn');
    if (closeWizardBtn) {
        closeWizardBtn.addEventListener('click', function() {
            closePolicyWizard();
        });
    }
    
    // 下一步按钮事件
    const nextStepBtn = document.getElementById('next-step-btn');
    if (nextStepBtn) {
        nextStepBtn.addEventListener('click', function() {
            goToNextStep();
        });
    }
    
    // 上一步按钮事件
    const prevStepBtn = document.getElementById('prev-step-btn');
    if (prevStepBtn) {
        prevStepBtn.addEventListener('click', function() {
            goToPrevStep();
        });
    }
    
    // 保存草稿按钮事件
    const saveDraftBtn = document.getElementById('save-draft-btn');
    if (saveDraftBtn) {
        saveDraftBtn.addEventListener('click', function() {
            savePolicyDraft();
        });
    }
    
    // 提交策略按钮事件
    const submitPolicyBtn = document.getElementById('submit-policy-btn');
    if (submitPolicyBtn) {
        submitPolicyBtn.addEventListener('click', function() {
            submitPolicy();
        });
    }
    
    // 生成向导步骤内容
    generateWizardStepsContent();
    
    // 编辑按钮事件（通过事件委托处理动态添加的编辑按钮）
    document.body.addEventListener('click', function(e) {
        if (e.target.closest('.edit-btn')) {
            e.preventDefault();
            e.stopPropagation();
            const editBtn = e.target.closest('.edit-btn');
            const policyId = parseInt(editBtn.dataset.id);
            if (!isNaN(policyId)) {
                openPolicyWizard(policyId);
            }
        }
    });
}

// 生成向导步骤内容
function generateWizardStepsContent() {
    const wizardContent = document.getElementById('wizard-content');
    
    // 步骤2: 检测内容
    const step2Content = `
        <div class="wizard-step wizard-step-2 hidden">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-text-primary mb-2">检测规则 <span class="text-danger">*</span></label>
                    <div id="rules-container" class="space-y-3">
                        <div class="bg-bg-secondary p-4 rounded-lg border border-border/10">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
                                <div>
                                    <label class="block text-xs text-text-secondary mb-1">规则类型</label>
                                    <select class="w-full px-2 py-1.5 text-sm border border-border/40 rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary">
                                        <option value="regex">正则表达式</option>
                                        <option value="file-size">文件大小</option>
                                        <option value="file-count">文件数量</option>
                                        <option value="rate-limit">访问频率</option>
                                        <option value="encryption">加密要求</option>
                                        <option value="tls-version">TLS版本</option>
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-xs text-text-secondary mb-1">规则描述</label>
                                    <input type="text" class="w-full px-2 py-1.5 text-sm border border-border/40 rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary" placeholder="简要描述此规则">
                                </div>
                            </div>
                            <div class="rule-params space-y-3">
                                <div>
                                    <label class="block text-xs text-text-secondary mb-1">正则表达式模式</label>
                                    <input type="text" class="w-full px-2 py-1.5 text-sm border border-border/40 rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary" placeholder="如: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}$">
                                </div>
                                <div class="flex items-center gap-2">
                                    <input type="checkbox" id="case-sensitive-1" class="rounded text-primary focus:ring-primary">
                                    <label for="case-sensitive-1" class="text-xs text-text-secondary">区分大小写</label>
                                </div>
                            </div>
                            <div class="flex justify-between items-center mt-3">
                                <div class="text-xs text-text-tertiary">规则 #1</div>
                                <button class="text-danger hover:text-danger/80 transition-colors" disabled>
                                    <i class="fa fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <button id="add-rule-btn" class="mt-3 w-full px-4 py-2 border border-dashed border-primary/30 text-primary hover:bg-primary/5 rounded-lg transition-colors duration-300">
                        <i class="fa fa-plus mr-1"></i> 添加规则
                    </button>
                </div>
                <div class="bg-bg-secondary p-4 rounded-lg">
                    <div class="flex items-center gap-2 mb-2">
                        <input type="checkbox" id="any-match" class="rounded text-primary focus:ring-primary" checked>
                        <label for="any-match" class="text-sm text-text-secondary">任一规则匹配时触发（OR逻辑）</label>
                    </div>
                    <div class="flex items-center gap-2">
                        <input type="checkbox" id="all-match" class="rounded text-primary focus:ring-primary">
                        <label for="all-match" class="text-sm text-text-secondary">所有规则匹配时触发（AND逻辑）</label>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 步骤3: 检测通道
    const step3Content = `
        <div class="wizard-step wizard-step-3 hidden">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-text-primary mb-2">选择检测协议 <span class="text-danger">*</span></label>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                        ${['http', 'https', 'ftp', 'smtp', 'email', 'ssh', 'api', 'custom'].map(protocol => {
                            const protocolName = protocol.toUpperCase();
                            let icon = 'fa-exchange';
                            if (protocol === 'http' || protocol === 'https') icon = 'fa-globe';
                            else if (protocol === 'ftp') icon = 'fa-file-archive-o';
                            else if (protocol === 'smtp' || protocol === 'email') icon = 'fa-envelope';
                            else if (protocol === 'ssh') icon = 'fa-key';
                            else if (protocol === 'api') icon = 'fa-code';
                            else if (protocol === 'custom') icon = 'fa-cogs';
                            
                            return `
                                <label class="flex flex-col items-center justify-center p-3 border border-border/40 rounded-lg cursor-pointer hover:border-primary/50 hover:bg-primary/5 transition-all duration-300">
                                    <input type="checkbox" name="protocol" value="${protocol}" class="sr-only peer">
                                    <i class="fa ${icon} text-lg mb-1 text-text-secondary peer-checked:text-primary"></i>
                                    <span class="text-sm peer-checked:text-primary">${protocolName}</span>
                                    <div class="mt-1 w-4 h-4 border border-border/40 rounded-full flex items-center justify-center peer-checked:border-primary peer-checked:bg-primary/10">
                                        <i class="fa fa-check text-xs text-primary opacity-0 peer-checked:opacity-100"></i>
                                    </div>
                                </label>
                            `;
                        }).join('')}
                    </div>
                </div>
                <div class="bg-bg-secondary p-4 rounded-lg">
                    <h4 class="text-sm font-medium text-text-primary mb-2">高级配置</h4>
                    <div class="space-y-3">
                        <div>
                            <label class="block text-xs text-text-secondary mb-1">触发阈值</label>
                            <input type="number" min="1" value="5" class="w-full px-2 py-1.5 text-sm border border-border/40 rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary">
                            <p class="text-xs text-text-tertiary mt-1">同一来源在监测周期内触发次数达到此值时执行动作</p>
                        </div>
                        <div>
                            <label class="block text-xs text-text-secondary mb-1">监测周期</label>
                            <select class="w-full px-2 py-1.5 text-sm border border-border/40 rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary">
                                <option value="minute">分钟</option>
                                <option value="hour" selected>小时</option>
                                <option value="day">天</option>
                                <option value="week">周</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 步骤4: 检测动作
    const step4Content = `
        <div class="wizard-step wizard-step-4 hidden">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-text-primary mb-2">命中管控 <span class="text-danger">*</span></label>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                        ${[
                            { value: 'block', label: '立即阻断', icon: 'fa-ban', desc: '阻止操作继续进行' },
                            { value: 'alert', label: '仅告警', icon: 'fa-exclamation-triangle', desc: '生成告警但不阻断' },
                            { value: 'record', label: '仅记录', icon: 'fa-history', desc: '仅记录操作不告警' }
                        ].map(action => `
                            <label class="flex flex-col p-3 border border-border/40 rounded-lg cursor-pointer hover:border-primary/50 hover:bg-primary/5 transition-all duration-300">
                                <input type="radio" name="control-action" value="${action.value}" class="sr-only peer" checked>
                                <i class="fa ${action.icon} text-lg mb-1 text-text-secondary peer-checked:text-primary"></i>
                                <span class="font-medium text-sm mb-1 peer-checked:text-primary">${action.label}</span>
                                <span class="text-xs text-text-tertiary">${action.desc}</span>
                            </label>
                        `).join('')}
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-text-primary mb-2">通知通道</label>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        ${[
                            { value: 'email', label: '邮件通知', icon: 'fa-envelope' },
                            { value: 'sms', label: '短信通知', icon: 'fa-mobile' },
                            { value: 'system', label: '系统消息', icon: 'fa-bell' },
                            { value: 'api', label: 'API回调', icon: 'fa-exchange' }
                        ].map(channel => `
                            <label class="flex items-center p-3 border border-border/40 rounded-lg cursor-pointer hover:border-primary/50 hover:bg-primary/5 transition-all duration-300">
                                <input type="checkbox" name="notification" value="${channel.value}" class="rounded text-primary focus:ring-primary mr-2">
                                <i class="fa ${channel.icon} text-sm mr-2 text-text-secondary"></i>
                                <span class="text-sm">${channel.label}</span>
                            </label>
                        `).join('')}
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-text-primary mb-2">通知时机</label>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                        ${[
                            { value: 'real-time', label: '实时通知' },
                            { value: 'daily-summary', label: '每日汇总' },
                            { value: 'weekly-summary', label: '每周汇总' }
                        ].map(type => `
                            <label class="flex items-center p-3 border border-border/40 rounded-lg cursor-pointer hover:border-primary/50 hover:bg-primary/5 transition-all duration-300">
                                <input type="radio" name="notification-type" value="${type.value}" class="rounded text-primary focus:ring-primary mr-2">
                                <span class="text-sm">${type.label}</span>
                            </label>
                        `).join('')}
                    </div>
                </div>
            </div>
        </div>
    `;
    
    if (wizardContent) {
        wizardContent.innerHTML += step2Content + step3Content + step4Content;
    }
    
    // 添加规则按钮事件
    const addRuleBtn = document.getElementById('add-rule-btn');
    if (addRuleBtn) {
        addRuleBtn.addEventListener('click', function() {
            addNewRule();
        });
    }
    
    // OR/AND逻辑单选效果
    const anyMatchCheckbox = document.getElementById('any-match');
    const allMatchCheckbox = document.getElementById('all-match');
    if (anyMatchCheckbox && allMatchCheckbox) {
        anyMatchCheckbox.addEventListener('change', function() {
            if (this.checked) {
                allMatchCheckbox.checked = false;
            }
        });
        
        allMatchCheckbox.addEventListener('change', function() {
            if (this.checked) {
                anyMatchCheckbox.checked = false;
            }
        });
    }
}

// 添加新规则
function addNewRule() {
    const rulesContainer = document.getElementById('rules-container');
    if (!rulesContainer) return;
    
    const ruleCount = rulesContainer.children.length + 1;
    
    const newRuleHTML = `
        <div class="bg-bg-secondary p-4 rounded-lg border border-border/10 animate-fadeIn">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
                <div>
                    <label class="block text-xs text-text-secondary mb-1">规则类型</label>
                    <select class="w-full px-2 py-1.5 text-sm border border-border/40 rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary">
                        <option value="regex">正则表达式</option>
                        <option value="file-size">文件大小</option>
                        <option value="file-count">文件数量</option>
                        <option value="rate-limit">访问频率</option>
                        <option value="encryption">加密要求</option>
                        <option value="tls-version">TLS版本</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs text-text-secondary mb-1">规则描述</label>
                    <input type="text" class="w-full px-2 py-1.5 text-sm border border-border/40 rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary" placeholder="简要描述此规则">
                </div>
            </div>
            <div class="rule-params space-y-3">
                <div>
                    <label class="block text-xs text-text-secondary mb-1">正则表达式模式</label>
                    <input type="text" class="w-full px-2 py-1.5 text-sm border border-border/40 rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary" placeholder="如: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}$">
                </div>
                <div class="flex items-center gap-2">
                    <input type="checkbox" id="case-sensitive-${ruleCount}" class="rounded text-primary focus:ring-primary">
                    <label for="case-sensitive-${ruleCount}" class="text-xs text-text-secondary">区分大小写</label>
                </div>
            </div>
            <div class="flex justify-between items-center mt-3">
                <div class="text-xs text-text-tertiary">规则 #${ruleCount}</div>
                <button class="text-danger hover:text-danger/80 transition-colors remove-rule-btn">
                    <i class="fa fa-trash"></i>
                </button>
            </div>
        </div>
    `;
    
    // 创建临时元素以安全地解析HTML
    const tempElement = document.createElement('div');
    tempElement.innerHTML = newRuleHTML;
    
    // 获取生成的规则元素
    const ruleElement = tempElement.firstElementChild;
    
    // 添加到容器
    rulesContainer.appendChild(ruleElement);
    
    // 添加删除按钮事件
    const deleteBtn = ruleElement.querySelector('.remove-rule-btn');
    if (deleteBtn) {
        deleteBtn.addEventListener('click', function() {
            ruleElement.classList.add('animate-fadeOut');
            setTimeout(() => {
                rulesContainer.removeChild(ruleElement);
                // 更新规则编号
                updateRuleNumbers();
            }, 300);
        });
    }
    
    // 更新其他规则的删除按钮状态
    updateDeleteButtonsState();
}

// 更新规则编号
function updateRuleNumbers() {
    const rulesContainer = document.getElementById('rules-container');
    if (!rulesContainer) return;
    
    Array.from(rulesContainer.children).forEach((rule, index) => {
        const ruleNumberElement = rule.querySelector('.text-text-tertiary');
        if (ruleNumberElement) {
            ruleNumberElement.textContent = `规则 #${index + 1}`;
        }
    });
    
    // 更新删除按钮状态
    updateDeleteButtonsState();
}

// 更新删除按钮状态
function updateDeleteButtonsState() {
    const rulesContainer = document.getElementById('rules-container');
    if (!rulesContainer) return;
    
    const rules = rulesContainer.children;
    const deleteButtons = rulesContainer.querySelectorAll('.remove-rule-btn');
    
    // 只有一个规则时禁用删除按钮
    if (rules.length === 1 && deleteButtons.length > 0) {
        deleteButtons[0].setAttribute('disabled', 'disabled');
    } else {
        deleteButtons.forEach(btn => btn.removeAttribute('disabled'));
    }
}

// 进入下一步
function goToNextStep() {
    if (currentStep < totalSteps) {
        // 验证当前步骤
        if (validateCurrentStep()) {
            // 保存当前步骤数据
            saveCurrentStepData();
            
            currentStep++;
            updateWizardStepUI();
        } else {
            showNotification('请填写所有必填字段并确保格式正确', 'error');
        }
    }
}

// 返回上一步
function goToPrevStep() {
    if (currentStep > 1) {
        currentStep--;
        updateWizardStepUI();
    }
}

// 更新向导步骤UI
function updateWizardStepUI() {
    // 更新步骤指示器
    const stepIndicators = document.querySelectorAll('#policy-wizard-modal .w-8.h-8.rounded-full');
    const stepLines = document.querySelectorAll('#policy-wizard-modal .flex-1.h-1');
    const stepLabels = document.querySelectorAll('#policy-wizard-modal .mb-2 span');
    
    // 重置所有步骤
    stepIndicators.forEach((indicator, index) => {
        if (index + 1 === currentStep) {
            indicator.classList.add('bg-primary', 'text-white');
            indicator.classList.remove('bg-bg-secondary', 'text-text-secondary');
        } else if (index + 1 < currentStep) {
            indicator.classList.add('bg-primary', 'text-white');
            indicator.classList.remove('bg-bg-secondary', 'text-text-secondary');
        } else {
            indicator.classList.add('bg-bg-secondary', 'text-text-secondary');
            indicator.classList.remove('bg-primary', 'text-white');
        }
    });
    
    // 更新线条
    stepLines.forEach((line, index) => {
        if (index + 1 < currentStep) {
            line.classList.add('bg-primary');
            line.classList.remove('bg-bg-secondary');
        } else {
            line.classList.add('bg-bg-secondary');
            line.classList.remove('bg-primary');
        }
    });
    
    // 更新标签
    stepLabels.forEach((label, index) => {
        if (index + 1 === currentStep) {
            label.classList.add('text-primary', 'font-medium');
            label.classList.remove('text-text-secondary');
        } else if (index + 1 < currentStep) {
            label.classList.add('text-text-secondary');
            label.classList.remove('text-primary', 'font-medium');
        } else {
            label.classList.add('text-text-secondary');
            label.classList.remove('text-primary', 'font-medium');
        }
    });
    
    // 显示当前步骤内容
    document.querySelectorAll('.wizard-step').forEach((step, index) => {
        if (index === 0 && currentStep === 1) {
            // 步骤1在HTML中已经存在，不是通过generateWizardStepsContent生成的
            step.classList.remove('hidden');
        } else if (index + 1 === currentStep) {
            step.classList.remove('hidden');
        } else {
            step.classList.add('hidden');
        }
    });
    
    // 更新按钮状态
    const prevBtn = document.getElementById('prev-step-btn');
    const nextBtn = document.getElementById('next-step-btn');
    const submitBtn = document.getElementById('submit-policy-btn');
    
    if (prevBtn) {
        prevBtn.classList.toggle('hidden', currentStep === 1);
    }
    
    if (nextBtn && submitBtn) {
        nextBtn.classList.toggle('hidden', currentStep === totalSteps);
        submitBtn.classList.toggle('hidden', currentStep !== totalSteps);
    }
}

// 验证当前步骤
function validateCurrentStep() {
    switch (currentStep) {
        case 1:
            return validateStep1();
        case 2:
            return validateStep2();
        case 3:
            return validateStep3();
        case 4:
            return validateStep4();
        default:
            return true;
    }
}

// 验证步骤1: 基础信息
function validateStep1() {
    const nameInput = document.querySelector('#wizard-content input[placeholder="请输入策略名称"]');
    const typeSelect = document.querySelector('#wizard-content select[name="policy-type"]');
    const groupSelect = document.querySelector('#wizard-content select[name="policy-group"]');
    
    return nameInput && nameInput.value.trim() !== '' && 
           typeSelect && typeSelect.value !== '' && 
           groupSelect && groupSelect.value !== '';
}

// 验证步骤2: 检测内容
function validateStep2() {
    const rulesContainer = document.getElementById('rules-container');
    return rulesContainer && rulesContainer.children.length > 0;
}

// 验证步骤3: 检测通道
function validateStep3() {
    const protocols = document.querySelectorAll('input[name="protocol"]:checked');
    return protocols.length > 0;
}

// 验证步骤4: 检测动作
function validateStep4() {
    const controlAction = document.querySelector('input[name="control-action"]:checked');
    return controlAction !== null;
}

// 保存当前步骤数据
function saveCurrentStepData() {
    switch (currentStep) {
        case 1:
            saveStep1Data();
            break;
        case 2:
            saveStep2Data();
            break;
        case 3:
            saveStep3Data();
            break;
        case 4:
            saveStep4Data();
            break;
    }
}

// 保存步骤1数据
function saveStep1Data() {
    const nameInput = document.querySelector('#wizard-content input[placeholder="请输入策略名称"]');
    const typeSelect = document.querySelector('#wizard-content select[name="policy-type"]');
    const groupSelect = document.querySelector('#wizard-content select[name="policy-group"]');
    const prioritySlider = document.getElementById('priority-slider');
    const descriptionTextarea = document.querySelector('#wizard-content textarea[placeholder="请输入策略描述"]');
    
    policyFormData = {
        ...policyFormData,
        name: nameInput?.value.trim() || '',
        type: typeSelect?.value || '',
        group: groupSelect?.value || '',
        priority: parseInt(prioritySlider?.value || '5'),
        description: descriptionTextarea?.value.trim() || '',
        lastModified: new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        }).replace(/\//g, '-')
    };
}

// 保存步骤2数据
function saveStep2Data() {
    const rulesContainer = document.getElementById('rules-container');
    if (!rulesContainer) {
        policyFormData.rules = [];
        return;
    }
    
    const rules = [];
    const ruleElements = rulesContainer.children;
    
    Array.from(ruleElements).forEach((ruleElement, index) => {
        const typeSelect = ruleElement.querySelector('select');
        const descriptionInput = ruleElement.querySelector('input[placeholder="简要描述此规则"]');
        const patternInput = ruleElement.querySelector('input[placeholder*="正则表达式"]');
        const caseSensitiveCheckbox = ruleElement.querySelector('input[type="checkbox"]');
        
        rules.push({
            type: typeSelect?.value || 'regex',
            pattern: patternInput?.value || '',
            description: descriptionInput?.value || `规则 ${index + 1}`,
            caseSensitive: caseSensitiveCheckbox?.checked || false
        });
    });
    
    policyFormData.rules = rules;
    
    // 保存逻辑关系
    const anyMatchCheckbox = document.getElementById('any-match');
    policyFormData.matchLogic = anyMatchCheckbox?.checked ? 'any' : 'all';
}

// 保存步骤3数据
function saveStep3Data() {
    const protocols = Array.from(document.querySelectorAll('input[name="protocol"]:checked'))
        .map(input => input.value);
    
    policyFormData.protocols = protocols.length > 0 ? protocols : ['http', 'https'];
    
    // 保存高级配置
    const thresholdInput = document.querySelector('.wizard-step-3 input[type="number"]');
    const periodSelect = document.querySelector('.wizard-step-3 select');
    
    policyFormData.advancedConfig = {
        threshold: parseInt(thresholdInput?.value || '5'),
        period: periodSelect?.value || 'hour'
    };
}

// 保存步骤4数据
function saveStep4Data() {
    const controlAction = document.querySelector('input[name="control-action"]:checked')?.value || 'alert';
    const notificationChannels = Array.from(document.querySelectorAll('input[name="notification"]:checked'))
        .map(input => input.value);
    const notificationType = document.querySelector('input[name="notification-type"]:checked')?.value || 'real-time';
    
    policyFormData.actions = {
        control: controlAction,
        notification: notificationChannels.length > 0 ? notificationChannels : ['system'],
        notificationType: [notificationType]
    };
}

// 保存草稿
function savePolicyDraft() {
    // 保存当前步骤数据
    saveCurrentStepData();
    
    // 标记为草稿
    policyFormData.status = 'disabled';
    policyFormData.isDraft = true;
    
    showNotification('策略草稿已保存', 'success');
    closePolicyWizard();
}

// 提交策略
function submitPolicy() {
    // 验证最后一步
    if (validateCurrentStep()) {
        // 保存最后一步数据
        saveCurrentStepData();
        
        // 标记为已启用
        policyFormData.status = 'enabled';
        policyFormData.isDraft = false;
        
        // 生成唯一ID（如果是新策略）
        if (!policyFormData.id) {
            policyFormData.id = Date.now();
        }
        
        // 保存到localStorage
        const policies = getPoliciesFromLocalStorage();
        
        if (isEditMode) {
            // 编辑现有策略
            const index = policies.findIndex(p => p.id === editPolicyId);
            if (index !== -1) {
                policies[index] = policyFormData;
            }
        } else {
            // 添加新策略
            policies.push(policyFormData);
        }
        
        // 保存回localStorage
        localStorage.setItem('policies', JSON.stringify(policies));
        
        // 重新渲染列表
        renderPolicyList(policies);
        
        // 显示成功通知
        showNotification(isEditMode ? '策略更新成功' : '策略创建成功', 'success');
        
        // 关闭向导
        closePolicyWizard();
    }
}

// 生成唯一ID
function generateUniqueId() {
    return Date.now() + Math.floor(Math.random() * 1000);
}

// 显示通知
function showNotification(message, type = 'info') {
    // 检查是否已存在通知容器
    let notificationContainer = document.getElementById('notification-container');
    if (!notificationContainer) {
        // 创建通知容器
        notificationContainer = document.createElement('div');
        notificationContainer.id = 'notification-container';
        notificationContainer.className = 'fixed top-4 right-4 z-50 max-w-md';
        document.body.appendChild(notificationContainer);
    }
    
    // 创建通知元素
    const notification = document.createElement('div');
    
    // 设置样式和内容
    notification.className = `bg-white rounded-lg shadow-lg p-4 mb-3 transform transition-all duration-500 animate-fadeIn translate-y-[-20px] opacity-0`;
    
    // 根据类型设置图标和背景色
    let iconClass = 'fa-info-circle text-blue-500';
    let bgClass = '';
    
    switch (type) {
        case 'success':
            iconClass = 'fa-check-circle text-green-500';
            bgClass = 'bg-green-50';
            break;
        case 'error':
            iconClass = 'fa-exclamation-circle text-red-500';
            bgClass = 'bg-red-50';
            break;
        case 'warning':
            iconClass = 'fa-exclamation-triangle text-yellow-500';
            bgClass = 'bg-yellow-50';
            break;
    }
    
    notification.classList.add(...bgClass.split(' '));
    
    // 设置通知内容
    notification.innerHTML = `
        <div class="flex items-center">
            <i class="fa ${iconClass} mr-3 text-lg"></i>
            <div class="flex-1">
                <p class="text-sm">${message}</p>
            </div>
            <button class="ml-2 text-gray-400 hover:text-gray-600" onclick="this.closest('.animate-fadeIn').remove()">
                <i class="fa fa-times"></i>
            </button>
        </div>
    `;
    
    // 添加到容器
    notificationContainer.appendChild(notification);
    
    // 触发动画
    setTimeout(() => {
        notification.classList.remove('translate-y-[-20px]', 'opacity-0');
    }, 10);
    
    // 自动关闭
    setTimeout(() => {
        notification.classList.add('translate-y-[-20px]', 'opacity-0');
        setTimeout(() => {
            notification.remove();
        }, 500);
    }, 3000);
}

// 确保在应用初始化时初始化策略向导
function ensureWizardInitialized() {
    // 检查是否已初始化
    if (typeof initPolicyWizard === 'function' && !window.wizardInitialized) {
        initPolicyWizard();
        window.wizardInitialized = true;
    }
}

// 应用主初始化函数
function init() {
    // 重置分页状态
    resetPagination();
    
    // 绑定事件监听器
    bindEventListeners();
    
    // 初始化交互
    initInteractions();
    
    // 加载并显示策略列表
    const policies = getPoliciesFromLocalStorage();
    renderPolicyList(policies);
    
    // 更新总数显示
    updateTotalCount();
    
    // 初始化策略向导
    ensureWizardInitialized();
}

// 在init函数中添加对策略向导初始化的调用（如果需要扩展init功能）
if (typeof init === 'function') {
    const originalInit = init;
    window.init = function() {
        originalInit();
        ensureWizardInitialized();
    };
}